<template>
  <div>
    <div class="gl_searchBox gl_mb_15">
      <el-row :gutter="20">
        <el-col :md="6" :lg="4">
          <p>按项目级别选择</p>
          <el-cascader v-model="project" :options="eventOptions" :props="{ value: 'id', label: 'name', checkStrictly: true }" size="mini" style="width: 100%" @change="changeProject()" />
        </el-col>
        <el-col :md="6" :lg="4">
          <p>按所属机构选择</p>
          <el-select v-model="Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO.DelegationId" size="mini" placeholder="全部" filterable @change="getPersonalData()">
            <el-option label="全部" value="" />
            <el-option v-for="item in mechanisms" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-col>
        <!-- 机构名称 -->
        <el-col :md="6" :lg="4">
          <p>选手名称/手机号</p>
          <el-input v-model="Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO.Filter" placeholder="请输入" size="mini" clearable @change="getPersonalData()" />
        </el-col>
        <el-col :md="4" :lg="2">
          <!-- 查询按钮 -->
          <el-button style="margin-top:27px" type="primary" size="mini" @click="getPersonalData()">查询</el-button>
        </el-col>
      </el-row>
    </div>
    <el-row class="gl_mb_15">
      <el-col align="right">
        <el-button :loading="competitionLoading" type="warning" size="mini" @click="exportCompetition()">导出参赛人员表</el-button>
        <el-button :loading="amountLoading" type="warning" size="mini" @click="exportamount()">导出保险信息表</el-button>
        <el-button :loading="athleteLoading" type="warning" size="mini" @click="exportAthlete()">导出选手信息表</el-button>
        <el-button :loading="entryLoading" type="warning" size="mini" @click="exportSignUp()">导出报名信息表</el-button>
        <el-button :loading="orderLoading" type="success" size="mini" @click="exportOrder('order')">导出秩序册1</el-button>
        <el-button :loading="orderLoading2" type="success" size="mini" @click="exportOrder('order2')">导出秩序册2</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="tableData" stripe size="mini">
      <el-table-column type="index" width="50" align="center" />
      <el-table-column prop="imagePath" label="头像" width="90" align="center">
        <template slot-scope="{row}">
          <img v-if="row.imagePath" width="40" :src="getStaticFileUrl(row.imagePath)">
          <img v-else width="40" src="@/assets/images/person_default.png">
          <!-- <el-button v-if="isNoVersion" type="text" size="mini" @click="generateQRCode(row)">生成二维码</el-button> -->
        </template>
      </el-table-column>
      <el-table-column prop="name" label="选手姓名" min-width="120" />
      <el-table-column prop="genderDes" label="性别" width="50" align="center" />
      <el-table-column prop="phoneNumber" label="手机号" width="100" align="center" />
      <template v-if="competitionInfo.isFinal && competitionInfo.parentId">
        <el-table-column prop="subCompetitionName" label="赛区" width="100" align="center" />
      </template>
      <el-table-column prop="idCardNumber" label="证件号" width="150" align="center" />
      <el-table-column prop="delegationName" label="机构全称" />
      <el-table-column prop="delegationShotName" label="机构简称" align="center" />
      <el-table-column prop="coaches" label="教练" width="160">
        <template slot-scope="{row}">
          <p v-for="(item, index) in row.coaches" :key="item.id">
            <span>{{ item.official.name }}{{ item.official.phoneNumber ? '/' + item.official.phoneNumber : '' }}</span>
            <span v-if="index != row.coaches.length - 1">；</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column prop="leaders" label="领队" width="160">
        <template slot-scope="{row}">
          <p v-for="(item, index) in row.leaders" :key="item.id">
            <span>{{ item.official.name }}{{ item.official.phoneNumber ? '/' + item.official.phoneNumber : '' }}</span>
            <span v-if="index != row.leaders.length - 1">；</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column fixed="right" prop="events" label="参赛项目" width="320">
        <!-- <template slot-scope="{row}">
          <p v-if="row.hasI" class="title">个人项目</p>
          <div v-for="(item, index) in row.events" :key="index">
            <p v-if="item.registerTypeCode == 'I'">
              <span>{{ item.longName }}</span>
              <span v-if="index != row.events.length - 1">；</span>
            </p>
          </div>
          <p v-if="row.hasT" class="title">团体项目</p>
          <div v-for="(item, index) in row.events" :key="item.id">
            <p v-if="item.registerTypeCode != 'I'">
              <span>{{ item.longName }}</span>
              <span v-if="index != row.events.length - 1">；</span>
            </p>
          </div>
        </template> -->
        <template slot-scope="{row}">
          <p v-if="row.hasI" class="title">个人项目</p>
          <div v-for="(item, index) in row.entryEventNames" :key="index">
            <p v-if="item.eventRegisterTypeCode == 'I'">
              <span>{{ item.eventLongName }}</span>
              <span v-if="item.eventWeightClassName">{{ ' (' + item.eventWeightClassName + ') ' }}</span>
              <span v-if="item.teamNo">{{ item.teamNo }}组</span>
              <span v-if="index != row.entryEventNames.length - 1">；</span>
            </p>
          </div>
          <p v-if="row.hasT" class="title">团体项目</p>
          <div v-for="(item, index) in row.entryEventNames" :key="item.id">
            <p v-if="item.eventRegisterTypeCode != 'I'">
              <span>{{ item.eventLongName }}</span>
              <span v-if="item.eventWeightClassName">{{ ' (' + item.eventWeightClassName + ') ' }}</span>
              <span v-if="item.teamNo">{{ item.teamNo }}组</span>
              <span v-if="index != row.entryEventNames.length - 1">；</span>
            </p>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-row class="gl_pt_20" style="text-align: center;">
      <el-pagination
        :current-page="Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO.Page"
        :page-size="Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO.MaxResultCount"
        :total="totalPage"
        layout="total,sizes,prev,pager,next,jumper"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="sizeChange"
        @current-change="pageIndexChange"
      />
    </el-row>

    <QRview ref="QRview" :qr-code-text="qrCodeText" />
  </div>
</template>
<script>
import { api_GET_DownLoadFileAddHeader } from '@/extend/api/file';
import { errorText } from '@/lib';
import { mapState } from 'vuex';
import QRview from './QRview';
import {
  api_GET_EventsManagementCategory, // 获取项目级别下拉列表
  api_GET_EventsManagementEntryDelegationListByCompetitionCompetitionId, // 获取机构下拉列表
  api_GET_EventsManagementCompetitionEntryDataCompAthleteData // 获取参赛人员列表
} from '@/extend/api/gameswaggerApi/app.js';
import {
  Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO
} from '@/lib/form/game/swaggerForm';
export default {
  name: 'Confirmed',
  components: {
    QRview
  },
  props: {
    competitionInfo: {
      type: Object,
      default () {
        return {};
      }
    }
  },
  data() {
    return {
      entryLoading: false,
      athleteLoading: false,
      amountLoading: false,
      competitionLoading: false,
      orderLoading: false,
      orderLoading2: false,
      Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO: new Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO(),
      loading: false,
      totalPage: 0,
      isNoVersion: false,
      qrCodeText: '',
      project: [''], // 项目级别选中项
      mechanisms: [], // 所属机构下拉列表
      eventOptions: [], // 项目级别下拉列表
      tableData: []
    };
  },
  computed: {
    ...mapState({
      tenantId: state => state.user.tenantId
    })
  },
  created() {
    if (process.env.VUE_APP_DIREVTOR !== 'version') {
      this.isNoVersion = true;
    }
    this.getEventList(); // 获取项目级别
    this.getGroup(); // 获取机构下拉列表
    this.getPersonalData(); // 获取参赛人员
  },
  methods: {
    // 查询
    getPersonalData(page) {
      var that = this;
      that.loading = true;
      that.Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO.Page = page || 1;
      that.Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO.SkipCount = (that.Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO.Page - 1) * that.Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO.MaxResultCount;
      that.Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO.CompetitionId = that.$route.params.id;
      that.Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO.IsEntryEventNameMode = true;
      api_GET_EventsManagementCompetitionEntryDataCompAthleteData(that.Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO).then(res => {
        that.tableData = res.items || [];
        for (var i = 0; i < res.items.length; i++) {
          var item = res.items[i];
          // item.events.forEach(htem => {
          //   if (htem.registerTypeCode === 'I') {
          //     item['hasI'] = true;
          //   }
          //   if (htem.registerTypeCode !== 'I') {
          //     item['hasT'] = true;
          //   }
          // });
          item.entryEventNames.forEach(htem => {
            if (htem.eventRegisterTypeCode === 'I') {
              item['hasI'] = true;
            }
            if (htem.eventRegisterTypeCode !== 'I') {
              item['hasT'] = true;
            }
          });
        }
        that.totalPage = res.totalCount;
        that.loading = false;
      }, () => {
        that.loading = false;
        that.$message({ type: 'error', message: '获取个人明细失败！' });
      });
    },
    // 获取机构下拉列表
    getGroup() {
      const gameId = this.$route.params.id;
      api_GET_EventsManagementEntryDelegationListByCompetitionCompetitionId(gameId).then(res => {
        this.mechanisms = res;
      });
    },
    // 获取项目级别
    getEventList() {
      const eventVO = {};
      eventVO.CompetitionId = this.$route.params.id;
      eventVO.IncludeEventGroup = true;
      eventVO.IncludeEvent = true;
      api_GET_EventsManagementCategory(eventVO).then(res => {
        const eventList = res.items || [];
        this.eventOptions = [
          {
            id: '',
            name: '全部'
          }
        ];
        const eventOptions = this.handleOptionWidthChooseEvent(eventList);
        this.eventOptions = [...this.eventOptions, ...eventOptions];
      }, () => {
        this.$message({ type: 'error', message: '获取项目列表失败！' });
      });
    },
    // 处理项目级联选择option
    handleOptionWidthChooseEvent(eventList) {
      for (let i = 0; i < eventList.length; i++) {
        const item = eventList[i];
        item.children = item.eventGroups;
        for (let j = 0; j < item.children.length; j++) {
          // eslint-disable-next-line prefer-const
          let jtem = item.children[j];
          for (let k = 0; k < jtem.events.length; k++) {
            // eslint-disable-next-line prefer-const
            let ktem = jtem.events[k];
            ktem.name = ktem.longName || ktem.name;
          }
          jtem.children = jtem.events;
        }
      }
      return eventList;
    },
    // 改变选中的项目级别
    changeProject() {
      this.Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO.CategoryId = this.project[0] || '';
      this.Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO.EventGroupId = this.project[1] || '';
      this.Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO.EventId = this.project[2] || '';
      this.getPersonalData();
    },
    exportCompetition() {
      var that = this;
      this.competitionLoading = true;
      const tempUrl = `/api/excel`;
      const fileName = '参赛人员表' + '.xlsx';
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, { ReportName: 'ComAthleteEntryExcelV2', CompetitionId: this.$route.params.id }).then(res => {
        that.competitionLoading = false;
      }).catch(error => {
        that.competitionLoading = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    },
    exportAthlete() {
      var that = this;
      this.athleteLoading = true;
      const tempUrl = `/api/excel`;
      const fileName = '选手信息表' + '.xlsx';
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, { ReportName: 'ComAthleteEntryExcel', CompetitionId: this.$route.params.id }).then(res => {
        that.athleteLoading = false;
      }).catch(error => {
        that.athleteLoading = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    },
    exportSignUp() {
      var that = this;
      this.entryLoading = true;
      const tempUrl = `/api/excel`;
      const fileName = '报名信息表' + '.xlsx';
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, { ReportName: 'ComAthleteEntryDetailExcel', CompetitionId: this.$route.params.id }).then(res => {
        that.athleteLoading = false;
      }).catch(error => {
        that.athleteLoading = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    },
    exportamount() {
      var that = this;
      this.amountLoading = true;
      const tempUrl = `/api/excel`;
      const fileName = '保险信息表' + '.xlsx';
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, { ReportName: 'ComAthleteEntryDetailAmount', CompetitionId: this.$route.params.id }).then(res => {
        that.amountLoading = false;
      }).catch(error => {
        that.amountLoading = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    },
    exportOrder(code) {
      var that = this;
      if (code === 'order') {
        this.orderLoading = true;
        const tempUrl = `/api/app/events-management/report`;
        const fileName = '秩序册1' + '.doc';
        api_GET_DownLoadFileAddHeader(tempUrl, fileName, { ReportName: 'Programme', Format: 'DOC', CompetitionId: this.$route.params.id }).then(res => {
          that.orderLoading = false;
        }).catch(error => {
          that.orderLoading = false;
          errorText(error).then(function(text) {
            that.$message({ type: 'error', message: text });
          });
        });
      } else {
        this.orderLoading2 = true;
        const tempUrl = `/api/app/events-management/report`;
        const fileName = '秩序册2' + '.doc';
        api_GET_DownLoadFileAddHeader(tempUrl, fileName, { ReportName: 'ProgrammeByEvent', Format: 'DOC', CompetitionId: this.$route.params.id }).then(res => {
          that.orderLoading2 = false;
        }).catch(error => {
          that.orderLoading2 = false;
          errorText(error).then(function(text) {
            that.$message({ type: 'error', message: text });
          });
        });
      }
    },
    // 图片回显
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 生成二维码
    generateQRCode(row) {
      var competitionId = this.$route.params.id;
      var id = this.tenantId;
      var text = WEB_CONFIG.VUE_APP_API_CERTIFICAT + '?p=' + row.idCardNumber + ',' + row.idCardTypeCode + ',' + competitionId + ',' + id;
      this.qrCodeText = text;
      this.$refs.QRview.open();
    },
    // 分页
    sizeChange: function(MaxResultCount) {
      this.Api_GET_EventsManagementCompetitionEntryDataCompAthleteDataQO.MaxResultCount = MaxResultCount;
      this.getPersonalData();
    },
    pageIndexChange(currentPage) {
      this.getPersonalData(currentPage);
    }
  }
};
</script>

<style lang="scss" scoped>
.title {
  font-size: 12px;
  font-weight: bold;
}
</style>
